package com.junjie.base.http;

import com.junjie.base.tool.PropertiesUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

import java.io.IOException;
import java.security.cert.CertificateException;

/**
 * 服务的主入口
 *
 * @author superzhan
 */
public final class MainServer {

    /*是否使用https协议*/
    static boolean SSL;
    /*运行端口号*/
    static int PORT;

    public static void run() {

        EventLoopGroup bossGroup = null;
        EventLoopGroup workerGroup = null;
        try {

            SSL = System.getProperty("ssl") != null;
            PORT = Integer.parseInt(System.getProperty("port", SSL ? PropertiesUtil.getProperty("ssl_port") : PropertiesUtil.getProperty("port")));
            // Configure SSL.
            final SslContext sslCtx;
            if (SSL) {
                SelfSignedCertificate ssc = new SelfSignedCertificate();
                sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
            } else {
                sslCtx = null;
            }
            //----------------------------------------------------------
            //bossGroup线程数设置
            if (PropertiesUtil.getProperty("bossGroup") == null) {
                bossGroup = new NioEventLoopGroup();
            } else {
                bossGroup = new NioEventLoopGroup(Integer.parseInt(PropertiesUtil.getProperty("bossGroup")));
            }
            //workerGroup线程数设置
            if (PropertiesUtil.getProperty("workerGroup") == null) {
                workerGroup = new NioEventLoopGroup();
            } else {
                workerGroup = new NioEventLoopGroup(Integer.parseInt(PropertiesUtil.getProperty("workerGroup")));
            }

            ServerBootstrap b = new ServerBootstrap();
            b.option(ChannelOption.SO_BACKLOG, 1024);
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ServerInitializer(sslCtx));

            Channel ch = b.bind(PORT).sync().channel();

            System.err.println("Open your web browser and navigate to " + (SSL ? "https" : "http") + "://127.0.0.1:" + PORT + '/');

            ch.closeFuture().sync();

        } catch (CertificateException | IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
